<!--
 * @Date: 2025-09-03 22:24:23
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-11-17 00:26:24
 * @FilePath: /admin-vue/src/components/ad/ad-data-table.vue
-->
<script setup lang="ts" generic="T">
import type { DataTableColumns, DataTableFilterState, DataTableSortState } from 'naive-ui'

// 定义组件 props
const { load, params } = defineProps<{
  collection: ResponsePageResult<T> | undefined
  columns: DataTableColumns<T>
  load: () => void
  params: Record<string, any>
  loading: boolean
}>()


const search = () => {
  params.page = 1
  load()
}

const handleSorterChange = (options: DataTableSortState | DataTableSortState[] | null) => search()

const handleFiltersChange = (filters: DataTableFilterState) => {
  Object.entries(filters).map(([k, v]) => (params[k] = v))
  search()
}
const handlePageChange = (qty: number) => {
  params.page = qty
  load()
}
const handlePageSizeChange = (qty: number) => {
  params.per_page = qty
  search()
}

onMounted(() => {
  load()
})


</script>

<template>
  <n-card size="small" class="h-full">
    <template #header>
      <NSpace justify="space-between">
        <NSpace>
          <slot name="button"></slot>
        </NSpace>
        <NInput type="text" v-model:value="params.key" @keyup.enter="search()">
          <template #suffix>
            <icon-local-search class="cursor-pointer" @click="search()" />
          </template>
        </NInput>
      </NSpace>
    </template>

    <n-data-table
      class="sm:h-full"
      remote
      flex-height
      :loading="loading"
      size="small"
      :scroll-x="962"
      :columns="columns"
      :data="collection?.data as Record<string, any>[]"
      :row-key="(row: any) => row.id"
      :pagination="{
        page: collection?.meta.current_page,
        pageSize: collection?.meta.per_page,
        pageCount: collection?.meta.last_page,
        itemCount: collection?.meta.total,
        showSizePicker: true,
        pageSizes: [5, 10, 15, 30, 50],
        prefix: (page: any) => $t('datatable.itemCount', { total: page.itemCount }),
      }"
      @update:filters="handleFiltersChange"
      @update:page="handlePageChange"
      @update:page-size="handlePageSizeChange"
      @update:sorter="handleSorterChange"
    />
  </n-card>
</template>
